package com.example.campuslink.ui.activity

import android.content.Context
import android.content.Intent
import android.provider.MediaStore
import android.text.Editable
import android.text.InputType
import android.text.Spannable
import android.text.SpannableStringBuilder
import android.text.style.ImageSpan
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.adpter.CommendEmojiAdapter
import com.example.campuslink.commen.adpter.InvitationCallUserListAdapter
import com.example.campuslink.commen.adpter.InvitationCommendAdapter
import com.example.campuslink.commen.adpter.InvitationImageAdapter
import com.example.campuslink.commen.db.invitation.InvitationTable
import com.example.campuslink.commen.interfaces.CommendPublic
import com.example.campuslink.commen.tools.CommendEmoji
import com.example.campuslink.commen.tools.Sp
import com.example.campuslink.commen.tools.SpacesItemButtonDecoration
import com.example.campuslink.commen.tools.SpacesItemEndDecoration
import com.example.campuslink.commen.tools.putExtraKey
import com.example.campuslink.databinding.ActivityInvitationDetailBinding
import com.example.campuslink.viewModel.InvitationDetailViewModel

class InvitationDetailActivity :
    BaseActivity<ActivityInvitationDetailBinding, InvitationDetailViewModel>(
        InvitationDetailViewModel::class.java,
        R.layout.activity_invitation_detail,
        BR.viewModel
    ), CommendPublic {
    private var imgAdapter: InvitationImageAdapter? = null
    private var invitation: InvitationTable? = null
    private val PICK_IMAGE_REQUEST = 1
    private var path = ""
    private var invitationCallUserAdapter: InvitationCallUserListAdapter? = null
    private val emojiList = CommendEmoji.emojiTitleList
    private var commendEmojiAdapter: CommendEmojiAdapter? = null
    private var invitationcommendAdapter: InvitationCommendAdapter? = null
    override fun initView() {
        initData()
        observe()
        mViewDataBinding?.vpInvitationImg?.adapter = imgAdapter
        mViewDataBinding?.tvInvitationType?.text = invitation?.invitationType
//        mViewDataBinding?.tvCommendCount?.text = "共有${mViewModel?.commendCount?.value}条评论"
        mViewDataBinding?.tvInvitationContent?.text = invitation?.invitationContent
        mViewDataBinding?.rvCallUserList?.adapter = invitationCallUserAdapter
        mViewDataBinding?.rvCallUserList?.layoutManager =
            LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false)
        if (invitation?.userNumber == Sp.getString(this, "userNumber", "") ?: "") {
            mViewDataBinding?.btnAttention?.visibility = View.GONE
        } else {
            mViewDataBinding?.btnAttention?.visibility = View.VISIBLE
        }

        mViewDataBinding?.rvCallUserList?.addItemDecoration(SpacesItemEndDecoration(10))
        mViewDataBinding?.rvEmoji?.adapter = commendEmojiAdapter
        mViewDataBinding?.rvEmoji?.layoutManager =
            GridLayoutManager(this, 4)
        mViewDataBinding?.editCommend?.setOnClickListener({
            mViewModel?.setEditStatus("None")
        })
        mViewDataBinding?.rvEmoji?.addItemDecoration(SpacesItemEndDecoration(10))
        mViewDataBinding?.rvCommend?.adapter = invitationcommendAdapter
        mViewDataBinding?.rvCommend?.layoutManager = LinearLayoutManager(this)
        mViewDataBinding?.rvCommend?.addItemDecoration(SpacesItemButtonDecoration(30))
        onClick()
    }


    fun openGallery() {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }

    private fun observe() {
        mViewModel?.attentionStatus?.observe(this) {
            mViewDataBinding?.btnAttention?.text = it
        }
        mViewModel?.commendCount?.observe(this) {
            mViewDataBinding?.tvCommendCount?.text =
                "共有${it}条评论"

        }
        mViewModel?.firstCommendList?.observe(
            this
        ) {
            if (it != null) {
                invitationcommendAdapter?.setListData(it)
            }
        }
        mViewModel?.emojiList?.observe(this) {
            setEmoji(it)
        }
        mViewModel?.callUserNumber?.observe(this) {
            if (it != null) {
                mViewDataBinding?.tvCallUserNumber?.text = it
            }
        }
        mViewModel?.userInfo?.observe(this) {
            if (it != null) {
                Glide.with(this).load(it.userAvatar)
                    .error(R.drawable.ic_empty)
                    .apply(RequestOptions.circleCropTransform())
                    .into(mViewDataBinding?.ivUserImg ?: return@observe)
            }
        }
        mViewModel?.nowNumberInfo?.observe(this) {
            Glide.with(this).load(it.userAvatar)
                .error(R.drawable.ic_empty)
                .apply(RequestOptions.circleCropTransform())
                .into(mViewDataBinding?.ivUserImg2 ?: return@observe)
            mViewDataBinding?.tvUserName?.text = it.userName
        }
        mViewModel?.userInfoList?.observe(this) {
            if (it.isNotEmpty()) {
                invitationCallUserAdapter?.setListData(it)
            }
        }
        mViewModel?.choiceImage?.observe(this) {
            if (it.isNotEmpty()) {
                Glide.with(this).load(it)
                    .error(R.drawable.ic_empty)
                    .apply(RequestOptions.circleCropTransform())
                    .into(mViewDataBinding?.ivCommendImg ?: return@observe)
            }
        }
        mViewModel?.editStatus?.observe(this) {
            when (it) {
                "openImg" -> {
                    mViewDataBinding?.rvCallUserList?.visibility = View.GONE
                    mViewDataBinding?.rvEmoji?.visibility = View.GONE
                    mViewDataBinding?.ivCommendImg?.visibility = View.VISIBLE
                }

                "callUser" -> {
                    mViewDataBinding?.rvCallUserList?.visibility = View.VISIBLE
                    mViewDataBinding?.rvEmoji?.visibility = View.GONE
                    mViewDataBinding?.ivCommendImg?.visibility = View.GONE
                }

                "emoji" -> {
                    mViewDataBinding?.rvCallUserList?.visibility = View.GONE
                    mViewDataBinding?.rvEmoji?.visibility = View.VISIBLE
                    mViewDataBinding?.ivCommendImg?.visibility = View.GONE
                }

                else -> {
                    mViewDataBinding?.rvCallUserList?.visibility = View.GONE
                    mViewDataBinding?.rvEmoji?.visibility = View.GONE
                    mViewDataBinding?.ivCommendImg?.visibility = View.VISIBLE
                }
            }
        }
    }

    private fun onClick() {
        mViewDataBinding?.btnAttention?.setOnClickListener({
            if (mViewModel?.attentionStatus?.value == "关注") {
                mViewModel?.addAttention()
            } else {
                mViewModel?.removeAttenttion()
            }
        })
        mViewDataBinding?.ivBack?.setOnClickListener({
            finish()
        })
        mViewDataBinding?.ivShare?.setOnClickListener({
            val textToShare = "这个帖子很有趣快点来观看吧"
            val intent = Intent(Intent.ACTION_SEND)
            intent.setType("text/plain")
            intent.putExtra(Intent.EXTRA_TEXT, textToShare)
            startActivity(Intent.createChooser(intent, "分享账号"))
        })
        mViewDataBinding?.ivOpenImg?.setOnClickListener({
            mViewModel?.setEditStatus("openImg")
            openGallery()
        })
        mViewDataBinding?.tvCall?.setOnClickListener({
            mViewModel?.setEditStatus("callUser")
            mViewModel?.getSchoolUserNumber(invitation?.userNumber ?: "")
        })
        mViewDataBinding?.ivEmojiBtn?.setOnClickListener({
            mViewModel?.setEditStatus("emoji")
        })
//        mViewDataBinding?.editCommend?.setOnClickListener({
//            mViewModel?.setParentPublic(true)
//            mViewDataBinding?.editCommend?.setText("")
//            mViewDataBinding?.editCommend?.inputType = InputType.TYPE_CLASS_TEXT
//            mViewDataBinding?.editCommend?.setHint("说说你的想法吧")
//        })
        mViewDataBinding?.editCommend?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入内容并发送请求
                val question = mViewDataBinding?.editCommend?.text.toString()
                if (question.isNotBlank()) {
                    if (mViewModel?.isParentPublic?.value ?: false) {
                        mViewModel?.addParentCommend(question, mViewModel?.choiceImage?.value ?: "")
                    }
                    mViewDataBinding?.editCommend?.setText("")
                    path = ""
                    mViewModel?.setImagePath("")
                }
                true // 表示已处理该事件
            } else {
                false // 未处理其他动作
            }
        }
    }

    fun setEmoji(emoji: String) {
        mViewDataBinding?.editCommend?.let { editText ->
            mViewDataBinding?.editCommend?.let { editText ->
                // 获取当前光标位置
                val cursorPosition = editText.selectionStart
                val emojiResId = CommendEmoji.getEmoji()[emoji] ?: return@let

                // 创建ImageSpan
                val drawable = ContextCompat.getDrawable(this, emojiResId)?.apply {
                    setBounds(0, 0, editText.lineHeight, editText.lineHeight)
                } ?: return@let

                val imageSpan = ImageSpan(drawable, ImageSpan.ALIGN_BASELINE)

                // 获取当前文本 (Editable)
                val editable = editText.text

                // 插入emoji (使用SpannableStringBuilder或直接操作Editable)
                if (editable is Editable) {
                    editable.insert(cursorPosition, " ") // 先插入一个空格作为占位
                    editable.setSpan(
                        imageSpan,
                        cursorPosition,
                        cursorPosition + 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    editText.setSelection(cursorPosition + 1) // 移动光标
                } else {
                    val spannable = SpannableStringBuilder(editText.text)
                    spannable.insert(cursorPosition, " ")
                    spannable.setSpan(
                        imageSpan,
                        cursorPosition,
                        cursorPosition + 1,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
                    )
                    editText.setText(spannable)
                    editText.setSelection(cursorPosition + 1)
                }
            }
        }
    }

    private fun initData() {
        mViewModel?.context = this
        mViewModel?.initDB(this)
        invitation = intent.getSerializableExtra(putExtraKey.INVITATION.key) as? InvitationTable
        if (invitation != null) {
            mViewModel?.getUserInfo(invitation?.userNumber ?: "")
        }
        imgAdapter = InvitationImageAdapter(mViewModel!!)
        imgAdapter?.setListData(invitation?.invitationImage?.toList() ?: listOf())
        invitationCallUserAdapter = InvitationCallUserListAdapter(mViewModel!!)
        commendEmojiAdapter = CommendEmojiAdapter(mViewModel!!)
        commendEmojiAdapter?.setListData(emojiList)
        invitationcommendAdapter = InvitationCommendAdapter(mViewModel!!, this)
        mViewModel?.getFirstCommend()
        mViewModel?.getAttentionStatus()
        mViewModel?.getNowNumberInfo()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            val selectedImageUri = data.data
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val contentResolver = contentResolver
            val cursor = contentResolver.query(selectedImageUri!!, projection, null, null, null)

            if (cursor != null) {
                cursor.moveToFirst()
                val columnIndex = cursor.getColumnIndex(projection[0])
                val imagePath = cursor.getString(columnIndex)
                cursor.close()

                // 此时imagePath就是所选图片的字符串形式的存储路径，可以在这里进行后续操作，如加载图片等
                path = imagePath
            }
        }
        mViewModel?.setImagePath(path)
    }

    override fun publicCommend(position: Int, handNumber: String) {
        mViewModel?.setParentPublic(false)
        mViewDataBinding?.editCommend?.requestFocus()
        // 2. 弹出软键盘
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mViewDataBinding?.editCommend, InputMethodManager.SHOW_IMPLICIT)


        if (handNumber != "") {
            mViewDataBinding?.editCommend?.hint = "回复@${handNumber}"
        } else {
            mViewDataBinding?.editCommend?.hint = "请输入评论"
        }
        mViewDataBinding?.editCommend?.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_DONE || actionId == EditorInfo.IME_ACTION_SEND) {
                // 获取输入内容并发送请求
                val question = mViewDataBinding?.editCommend?.text.toString()
                if (question.isNotBlank()) {
                    if (mViewModel?.isParentPublic?.value ?: false) {

                    } else {
                        mViewModel?.addChildCommend(
                            question,
                            mViewModel?.choiceImage?.value ?: "",
                            position,
                            handNumber ?: ""
                        )
                        mViewModel?.setParentPublic(true)
                    }
                    mViewDataBinding?.editCommend?.setText("")
                    mViewDataBinding?.editCommend?.hint = "请输入评论"
                    path = ""
                    mViewModel?.setImagePath("")
                }
                true // 表示已处理该事件
            } else {
                false // 未处理其他动作
            }
        }
    }
}